//
//  BlueToothViewController.m
//  LightControl
//
//  Created by CKF on 2025/6/30.
//

#import "BlueToothViewController.h"
#import "BabyBluetooth.h"
#import "CommonMethod.h"
@interface BlueToothViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)BabyBluetooth *baby;

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSMutableArray *scanEquipArray;
@property(nonatomic,strong)NSMutableArray *equipNameArray;
@property(nonatomic,strong)UILabel *uidLabel;
@property(nonatomic,strong)UILabel *f0Label;
@property(nonatomic,assign)int step;
@property(nonatomic,assign)NSString *uid;
@end

@implementation BlueToothViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.title = @"蓝牙";
    
    NSLog(@"随机字符串%@",[CommonMethod generateRandomHexString]);
//    NSString *nUid = @"423678213233320300F620435603F878";
//    nUid = @"4236782D3233320300F62C435603F878";
//    NSString *bufStr = @"F0000102030405120003010001aa5054";
//
//    NSMutableArray *decArray = [NSMutableArray new];
//    for (int i = 0; i<bufStr.length; i+=2) {
//        [decArray addObject:[NSNumber numberWithInteger:[CommonMethod hexToDecimal:[bufStr substringWithRange:NSMakeRange(i, 2)]]]];
//    }
//
//    uint8_t buffer[] = {0xF0, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x12, 0x00, 0x03, 0x01, 0x00, 0x01, 0xaa, 0x50, 0x54};
//    
//    int sec_key = [CommonMethod calculateSecKey:nUid];
//    
//    NSArray *arr = [CommonMethod encryptDataWithSeckey:sec_key buffer:buffer length:sizeof(buffer)-2];
//    
//    NSArray *arr2 = [CommonMethod encryptDataWithSeckey:sec_key intArray:decArray length:decArray.count-2];
//    
//    NSLog(@"%@",arr);
//
//    NSLog(@"%@",arr2);
    
//    NSLog(@"----------------------");
//    NSString *uu = @"00F4221150330054";
//    NSString *yy = [self getUUIDStr:uu];
//    
//    NSArray *ids = @[@"3AF2",@"2B34",@"0E61",@"504A",@"0054"];
//    NSString *idstr = [ids componentsJoinedByString:@""];
//    NSString *re = [CommonMethod reverseEveryTwoCharacters:idstr];
//    
//    NSString *reverseString = [CommonMethod reverseEveryTwoCharacters:idstr];
//    if ([[reverseString uppercaseString] hasPrefix:@"F2"] &&  [reverseString containsString:@"5054"]) {
//        NSRange range = [reverseString rangeOfString:@"5054"];
//        if (range.location == 14) {
//            NSString *macString = [reverseString substringWithRange:NSMakeRange(2, 12)];
//            NSMutableArray *macArray = [[NSMutableArray alloc]init];
//            for (int i=0; i<macString.length; i+=2) {
//                NSString *byte = [macString substringWithRange:NSMakeRange(i, 2)];
//                [macArray addObject:byte];
//            }
//            NSLog(@"111111    %@",[macArray componentsJoinedByString:@":"]);
//       
//        }else{
//           
//        }
//    }else{
//        
//    }
    
    
    _uidLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 30, KScreenWidth-20, 30)];
    [self.view addSubview:_uidLabel];
    _uidLabel.adjustsFontSizeToFitWidth = YES;
    _uidLabel.font = [UIFont systemFontOfSize:15];
    _uidLabel.textColor = [UIColor blackColor];
    _uidLabel.text = @"最终uid";
    
    _f0Label = [[UILabel alloc]initWithFrame:CGRectMake(10, 80, KScreenWidth-20, 120)];
    [self.view addSubview:_f0Label];
    _f0Label.adjustsFontSizeToFitWidth = YES;
    _f0Label.font = [UIFont systemFontOfSize:15];
    _f0Label.numberOfLines = 0;
    _f0Label.textColor = [UIColor blackColor];
    _f0Label.text = @"F0的数据:";
    

    _dataArray = [[NSMutableArray alloc]init];
//    UIButton *_selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    _selectBtn.frame = CGRectMake(10, 100, 100, 100);
//    [_selectBtn setTitle:@"发送F1广播" forState:0];
//    [_selectBtn setTitleColor:[UIColor redColor] forState:0];
//    [_selectBtn setBackgroundColor:[UIColor greenColor]];
//    [_selectBtn addTarget:self action:@selector(advertiseData) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:_selectBtn];
//    
//    
//    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    searchBtn.frame = CGRectMake(120, 100, 100, 100);
//    [searchBtn setTitle:@"扫码设备" forState:0];
//    [searchBtn setTitleColor:[UIColor redColor] forState:0];
//    [searchBtn setBackgroundColor:[UIColor greenColor]];
//    [searchBtn addTarget:self action:@selector(searchBtnAct) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:searchBtn];
//    
//    
//    UIButton *stopBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    stopBtn.frame = CGRectMake(230, 100, 120, 100);
//    [stopBtn setTitle:@"停止扫描设备" forState:0];
//    [stopBtn setTitleColor:[UIColor redColor] forState:0];
//    [stopBtn setBackgroundColor:[UIColor greenColor]];
//    [stopBtn addTarget:self action:@selector(stopBtnAct) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:stopBtn];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 200, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-mSafeAreaHeight-mNavBarHeight-80)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    
    _baby = [BabyBluetooth shareBabyBluetooth];
    [self babydelegate];

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _step==1?_dataArray.count:self.scanEquipArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell1"];
        UILabel *lebel = [[UILabel alloc]initWithFrame:CGRectMake(20, 30, [UIScreen mainScreen].bounds.size.width-40, 110)];
        lebel.textColor = [UIColor blackColor];
        lebel.numberOfLines = 0;
        lebel.font = [UIFont systemFontOfSize:14];
        lebel.tag = 999;
        [cell.contentView addSubview:lebel];
        
        UILabel *lebel2 = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, [UIScreen mainScreen].bounds.size.width-40, 30)];
        lebel2.textColor = [UIColor blackColor];
        lebel2.numberOfLines = 0;
        lebel2.font = [UIFont systemFontOfSize:17];
        lebel2.tag = 888;
        [cell.contentView addSubview:lebel2];
        
    }
//    NSDictionary *dic = [_dataArray objectAtIndex:indexPath.row];
    

    UILabel *label1 = [cell viewWithTag:999];
//    label1.text = dic[@"data"];
    label1.text = _step==1?[_dataArray objectAtIndex:indexPath.row][@"name"]:[self.equipNameArray objectAtIndex:indexPath.row];
    label1.textColor = [UIColor blackColor];
    
    
    UILabel *label2 = [cell viewWithTag:888];
//    label2.text = dic[@"name"];
    label2.text = _step==1?[_dataArray objectAtIndex:indexPath.row][@"data"]:[NSString stringWithFormat:@"mac地址:%@",[self.scanEquipArray objectAtIndex:indexPath.row]];
    label2.textColor = [UIColor blackColor];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *mac = [self.scanEquipArray objectAtIndex:indexPath.row];
    if(self.baby.peripheralManager.isAdvertising){
        [self.baby.peripheralManager stopAdvertising];
    }
    _step = 1;
    [self.dataArray removeAllObjects];
    NSString *sendMac = [mac stringByReplacingOccurrencesOfString:@":" withString:@""];
    NSArray *macArray = [[NSUserDefaults standardUserDefaults]objectForKey:@"macArray"];
    if (![macArray containsObject:sendMac]) {
        NSMutableArray *array =  [macArray mutableCopy];
        [array addObject:sendMac];
        [[NSUserDefaults standardUserDefaults]setObject:array forKey:@"macArray"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
    NSString *str = [NSString stringWithFormat:@"F3%@%@5054",sendMac,@"000102030405"];
    NSString *advStr = [self addPlaceholderString:str];;
    NSString *reverseStr = [CommonMethod reverseEveryTwoCharacters:advStr];
    NSMutableArray *uuidArray = [NSMutableArray new];
    for (int i = 0; i<reverseStr.length; i+=4) {
        NSString *subStr = [reverseStr substringWithRange:NSMakeRange(i, 4)];
        CBUUID *uuid = [CBUUID UUIDWithString:subStr];
        [uuidArray addObject:uuid];
    }
    NSLog(@"uuid ==== > %@",uuidArray);
    NSDictionary *advertisementData = @{
        CBAdvertisementDataServiceUUIDsKey :uuidArray,
        CBAdvertisementDataLocalNameKey:@"03"
    };
    [self.baby.peripheralManager startAdvertising:advertisementData];
   
}


-(NSMutableString *)addPlaceholderString:(NSString *)str{
    NSMutableString *mstr = [[NSMutableString alloc]initWithString:str];
    for (int i=0; i<52-str.length; i+=2) {
        [mstr appendString:[NSString stringWithFormat:@"%d",80+i/2]];
    }
    return mstr;
}

-(NSString *)convertToJsonData:(NSDictionary *)dict{
    NSLog(@"11111111111111%@",dict);
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}

-(void)searchBtnAct{
    self.baby.scanForPeripherals().begin().stop(10);
}

-(void)stopBtnAct{
    [self.baby cancelScan];
}

-(void)babydelegate{
    //中心模式
    __weak typeof(self) weakSelf = self;

    BabyRhythm *rhythm = [[BabyRhythm alloc]init];
    //设置扫描到设备的委托
    [_baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
       
        
        NSLog(@"搜索到了设备:%@",peripheral.name);
        NSLog(@"advertisementData==>%@",advertisementData);
        NSMutableDictionary *mdic = [[NSMutableDictionary alloc]initWithDictionary:advertisementData];
        if([mdic.allKeys containsObject:@"kCBAdvDataManufacturerData"]){
            NSData *data =  mdic[@"kCBAdvDataManufacturerData"];
            mdic[@"kCBAdvDataManufacturerData"] = [CommonMethod convertDataToHexStr:data];
        }
        if([mdic.allKeys containsObject:@"kCBAdvDataServiceData"]){
            NSDictionary *service = mdic[@"kCBAdvDataServiceData"];
            NSMutableDictionary *mservice = [NSMutableDictionary new];
            for (CBUUID *uuid in service.allKeys) {
                NSData *data =  service[uuid];
                [mservice setObject:[CommonMethod convertDataToHexStr:data] forKey:uuid.UUIDString];
            }
            [mdic removeObjectForKey:@"kCBAdvDataServiceData"];
            mdic[@"kCBAdvDataServiceData"] = mservice;
        }
        if([mdic.allKeys containsObject:@"kCBAdvDataServiceUUIDs"]){
            NSArray *uuids =  mdic[@"kCBAdvDataServiceUUIDs"];
            NSMutableArray *uuidArr = [NSMutableArray new];
            NSMutableString *uuidStr = [[NSMutableString alloc]init];
            for (int i = 0; i<uuids.count; i++) {
                CBUUID *uuid = [uuids objectAtIndex:i];
                [uuidArr addObject: uuid.UUIDString];
                [uuidStr appendString:uuid.UUIDString];
            }
            mdic[@"kCBAdvDataServiceUUIDs"] = uuidArr;
            if (uuidStr.length > 0 ) {
                if (weakSelf.step == 1) {
                    NSString *uid = [weakSelf getUUIDStr:uuidStr];
                    if (uid.length>0) {
                        weakSelf.uid = uid;
                        [weakSelf.dataArray addObject:@{@"name":peripheral.name.length>0?peripheral.name:@"无设备名",@"data":[weakSelf convertToJsonData:mdic]}];
                        [weakSelf.baby cancelScan];
                        weakSelf.uidLabel.text = [NSString stringWithFormat:@"最终uid:%@",uid];
                    }
                } else{
                    [weakSelf isSuitAbleEquipment:uuidStr withName:peripheral.name.length>0?peripheral.name:@"无设备名"];
                }
            }
        }
        NSLog(@"mdic===>%@",mdic);

    }];

    //过滤器
    //设置查找设备的过滤器
    [_baby setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
        //最常用的场景是查找某一个前缀开头的设备 most common usage is discover for peripheral that name has common prefix
        //if ([peripheralName hasPrefix:@"Pxxxx"] ) {
        //    return YES;
        //}
        //return NO;
        //设置查找规则是名称大于1 ， the search rule is peripheral.name length > 1
//        if (peripheralName.length >1) {
        return YES;

    }];
    
    //设置发现characteristics的descriptors的委托
    [_baby setBlockOnDiscoverDescriptorsForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristic, NSError *error) {
        NSLog(@"===characteristic name:%@",characteristic.service.UUID);
        for (CBDescriptor *d in characteristic.descriptors) {
            NSLog(@"CBDescriptor name is :%@",d.UUID);
        }
    }];
    //设置读取Descriptor的委托
    [_baby setBlockOnReadValueForDescriptors:^(CBPeripheral *peripheral, CBDescriptor *descriptor, NSError *error) {
        NSLog(@"Descriptor name:%@ value is:%@",descriptor.characteristic.UUID, descriptor.value);
    }];
    
    [_baby setBlockOnCancelAllPeripheralsConnectionBlock:^(CBCentralManager *centralManager) {
        NSLog(@"setBlockOnCancelAllPeripheralsConnectionBlock");
    }];
       
    [_baby setBlockOnCancelScanBlock:^(CBCentralManager *centralManager) {
        NSLog(@"setBlockOnCancelScanBlock");

        [weakSelf.tableView reloadData];
    
    }];
    
    //读取rssi的委托
    [_baby setBlockOnDidReadRSSI:^(NSNumber *RSSI, NSError *error) {
        NSLog(@"setBlockOnDidReadRSSI:RSSI:%@",RSSI);
    }];
    
    
    //设置beats break委托
    [rhythm setBlockOnBeatsBreak:^(BabyRhythm *bry) {
        NSLog(@"setBlockOnBeatsBreak call");
        
        //如果完成任务，即可停止beat,返回bry可以省去使用weak rhythm的麻烦
//        if (<#condition#>) {
//            [bry beatsOver];
//        }
        
    }];
    
    [_baby setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {
        switch (central.state) {
            case CBManagerStateUnknown:
                BabyLog(@">>>CBPeripheralManagerStateUnknown");
//                [weakSelf showBlueToothAlert];
                break;
            case CBManagerStateResetting:
                BabyLog(@">>>CBPeripheralManagerStateResetting");
                break;
            case CBManagerStateUnsupported:
                BabyLog(@">>>CBPeripheralManagerStateUnsupported");
                break;
            case CBManagerStateUnauthorized:
                BabyLog(@">>>CBPeripheralManagerStateUnauthorized");
                break;
            case CBManagerStatePoweredOff:
                BabyLog(@">>>CBPeripheralManagerStatePoweredOff");
                break;
            case CBManagerStatePoweredOn:
                BabyLog(@">>>CBPeripheralManagerStatePoweredOn");
                //发送centralManagerDidUpdateState通知
                break;
            default:
                break;
        }
    }];
    
    //设置beats over委托
    [rhythm setBlockOnBeatsOver:^(BabyRhythm *bry) {
        NSLog(@"setBlockOnBeatsOver call");
    }];
    
    //外设模式
    
    [_baby peripheralModelBlockOnPeripheralManagerDidUpdateState:^(CBPeripheralManager *peripheral) {
        switch (peripheral.state) {
            case CBManagerStateUnknown:
                BabyLog(@">>>CBPeripheralManagerStateUnknown");
                break;
            case CBManagerStateResetting:
                BabyLog(@">>>CBPeripheralManagerStateResetting");
                break;
            case CBManagerStateUnsupported:
                BabyLog(@">>>CBPeripheralManagerStateUnsupported");
                break;
            case CBManagerStateUnauthorized:
                BabyLog(@">>>CBPeripheralManagerStateUnauthorized");
                break;
            case CBManagerStatePoweredOff:
                BabyLog(@">>>CBPeripheralManagerStatePoweredOff");
                break;
            case CBManagerStatePoweredOn:
                BabyLog(@">>>CBPeripheralManagerStatePoweredOn");
                //发送centralManagerDidUpdateState通知
                [self performSelector:@selector(advertiseData) withObject:nil afterDelay:0.5];
                break;
            default:
                break;
        }
    }];

    [_baby peripheralModelBlockOnDidAddService:^(CBPeripheralManager *peripheral, CBService *service, NSError *error) {
        NSLog(@"peripheralModelDidAddService");
    }];
    
    [_baby peripheralModelBlockOnDidStartAdvertising:^(CBPeripheralManager *peripheral, NSError *error) {
        NSLog(@"peripheralModelDidStartAdvertising");
        weakSelf.baby.scanForPeripherals().begin().stop(10);
    }];
    
    [_baby peripheralModelBlockOnDidReceiveReadRequest:^(CBPeripheralManager *peripheral, CBATTRequest *request) {
        NSLog(@"peripheralModelDidReceiveReadRequest");
    }];
    
}

-(void)showBlueToothAlert{
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"提示" message:@"您尚未为此打开蓝牙权限,请前往打开" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url =  [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication]canOpenURL:url]) {
            [[UIApplication sharedApplication]openURL:url options:@{} completionHandler:nil];
        }
    }];

    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    
    //把action添加到actionSheet里
    [actionSheet addAction:action];
    [actionSheet addAction:cancel];
    //相当于之前的[actionSheet show];
    [self presentViewController:actionSheet animated:YES completion:nil];
}

//广播数据
-(void)advertiseData{
    _step = 0;
    [self.scanEquipArray removeAllObjects];
    [self.equipNameArray removeAllObjects];
    NSString *adv = @"F10001020304055054";
    NSString *advStr = [self addPlaceholderString:adv];
    
    NSString *reverseStr = [CommonMethod reverseEveryTwoCharacters:advStr];
    NSMutableArray *uuidArray = [NSMutableArray new];
    for (int i = 0; i<reverseStr.length; i+=4) {
        NSString *subStr = [reverseStr substringWithRange:NSMakeRange(i, 4)];
        CBUUID *uuid = [CBUUID UUIDWithString:subStr];
        [uuidArray addObject:uuid];
    }
    NSLog(@"uuid ==== > %@",uuidArray);
    NSDictionary *advertisementData = @{
        CBAdvertisementDataServiceUUIDsKey :uuidArray,
        CBAdvertisementDataLocalNameKey:@"01"
    };

    CBPeripheralManager *_peripheralManager = [_baby  peripheralManager];
    [_peripheralManager startAdvertising:advertisementData];
  
}

//满足F2
-(void)isSuitAbleEquipment:(NSString *)uuid withName:(NSString *)equipName {
    NSString *reverseString = [[CommonMethod reverseEveryTwoCharacters:uuid] uppercaseString];
    if ([[reverseString uppercaseString] hasPrefix:@"F2"] &&  [reverseString containsString:@"5054"]) {
        NSString *macString = [CommonMethod substringBetweenStart:@"F2" andLastEnd:@"5054" inString:reverseString];
        if (macString.length == 16) {
            NSMutableArray *macArray = [[NSMutableArray alloc]init];
            for (int i=0; i<12; i+=2) {
                NSString *subMac = [macString substringWithRange:NSMakeRange(i, 2)];
                [macArray addObject:subMac];
            }
            NSString *equipmentType = [macString substringWithRange:NSMakeRange(12, 4)];
            [self.scanEquipArray addObject:[macArray componentsJoinedByString:@":"]];
            [self.equipNameArray addObject:[NSString stringWithFormat:@"设备名:%@ 设备类型:%@",equipName,equipmentType]];
        }
    }
}


//满足F4
-(NSString *)getUUIDStr:(NSString *)uuid{
    NSString *reverseString = [[CommonMethod reverseEveryTwoCharacters:uuid] uppercaseString];
    if ([[reverseString uppercaseString] hasPrefix:@"F4"] && ([reverseString hasSuffix:@"5054"] || [reverseString hasSuffix:@"505400"] || [reverseString containsString:@"5054"])) {
//        NSRange range = [reverseString rangeOfString:@"5054"];
//        NSString *uuid = [reverseString substringToIndex:range.location];
//        NSString *result = [uuid substringFromIndex:2];
        NSString *result = [CommonMethod substringBetweenStart:@"F4" andLastEnd:@"5054" inString:reverseString];
        return result;
    }else{
        return @"";
    }
}

-(NSMutableArray *)scanEquipArray{
    if (!_scanEquipArray) {
        _scanEquipArray = [NSMutableArray new];
    }
    return _scanEquipArray;
}

-(NSMutableArray *)equipNameArray{
    if (!_equipNameArray) {
        _equipNameArray = [NSMutableArray new];
    }
    return _equipNameArray;
}


@end
